
Page({
  /**
   * 页面的初始数据
   */
  data: {
    token: "",
    baseImgUrl: getApp().globalData.IMG_URL,
    serverUrl: getApp().globalData.SERVER_URL,
    userInfo: {
      realname: "",
      avatar: ""
    },
    showLoading: true,
    showLoadingTxt: "努力加载中...",
    pageNo: 1,
    pageSize: 10,
    isRefresh: true,
    allPages: 0,
    // 业务部分
    orderAndGoodsList: Array,
    stateTxtColor: "color: #990000;"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const token = wx.getStorageSync('token')
    const user = wx.getStorageSync('userInfo');
    // console.error(JSON.parse(user));
    this.setData({ userInfo: JSON.parse(user), token: token });

    console.error(JSON.stringify(this.data));
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onPullDownRefresh()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 查询用户订单
    this.setData({ pageNo: 1, isRefresh: true })
    this.getOrderHistoryPageForCurrUser(this.data.pageNo, this.data.pageSize)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 查询用户订单
    if (this.data.allPages > this.data.pageNo) {
      var pageNum = this.data.pageNo + 1;
      this.getOrderHistoryPageForCurrUser(pageNum, this.data.pageSize)
      this.setData({ pageNo: pageNum, isRefresh: false })
    } else {
      console.info("没更多数据")
    }
  },
  gotoPage(param: any): void {
    let pagePath = param.currentTarget.dataset.path
    let storeId = param.currentTarget.dataset.tenantid
    console.error("storeId: " + storeId)
    wx.navigateTo({
      url: pagePath,
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  
        res.eventChannel.emit('acceptDataFromOpenerPage', { storeId: storeId })
      }
    })
  },
  openOrderDetail(param: any) {
    let item = param.currentTarget.dataset.value
    // console.error("item: " + JSON.stringify(item))
    // let pagePath = "/pages/order/orderDetail/orderDetail"
    wx.navigateTo({
      url: '/pages/order/orderDetail/orderDetail?orderNo=' + item.orderNo,
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  
        // res.eventChannel.emit('pageData', { orderNo: item.orderNo})
      }
    })
  },
  // 加载数据
  getOrderHistoryPageForCurrUser(pageNum: number, pageSize: number): void {
    var that = this
    const url = this.data.serverUrl + "fc/order/customer/historyPage"
    wx.request({
      url: url,
      method: 'GET',
      data: {
        pageNo: pageNum,
        pageSize: pageSize
      },
      header: {
        'content-type': 'application/json', // 默认值
        'X-Access-Token': this.data.token
      },
      success(res: any) {
        // console.error("success ==> " + JSON.stringify(res.data))
        wx.stopPullDownRefresh() //wx.startPullDownRefresh()
        if (res.data.code == 200) {
          that.setData({ allPages: res.data.result.pages })
          // console.info("total = " + res.data.result.total)
          // console.info("allPages = " + res.data.result.pages)

          const length = res.data.result.records.length
          if (length > 0) {
            for (let index = 0; index < length; index++) {
              const item = res.data.result.records[index]
              if (item != null) {
                var goodsNum = 0
                for (let index = 0; index < item.goodsList.length; index++) {
                  const goods = item.goodsList[index];
                  goodsNum = goodsNum + goods.saleNum;
                  // 处理方面
                  const cover = goods.goodsCover;
                  if (cover.includes(',')) {
                    const firstIndex = cover.indexOf(',');
                    const coverReal = cover.substring(0, firstIndex);
                    goods.goodsCover = coverReal
                  } else {
                    goods.goodsCover = cover
                  }
                }
                item.goodsListNum = goodsNum
              }
            }

            if (that.data.isRefresh) {// 刷新
              that.setData({ orderAndGoodsList: res.data.result.records })
              that.setData({ showLoading: false, showLoadingTxt: "努力加载中..." })
            } else {// 加载更多
              that.setData({ orderAndGoodsList: that.data.orderAndGoodsList.concat(res.data.result.records) })
              that.setData({ showLoading: false, showLoadingTxt: "努力加载中..." })
            }
            // console.error("加载更多：" + JSON.stringify(that.data.orderAndGoodsList))
          } else {
            if (that.data.isRefresh) {
              that.setData({ showLoading: true, showLoadingTxt: "暂无数据" })
            }
          }
        } else {
          console.info(JSON.stringify(res))
          that.setData({ showLoading: true, showLoadingTxt: res.data.msg })
        }
      },
      fail(err: any) {
        that.setData({ showLoading: true, showLoadingTxt: err.errMsg })
      }
    })
  },
  // 操作订单
  orderOptByOrderId(orderId: String, optType: String): void {
    console.error("orderOptByOrderId -> optType: " + optType + ", orderId:" + orderId)

    var that = this
    const url = this.data.serverUrl + "fc/order/customer/updateSate"
    wx.request({
      url: url,
      method: 'PUT',
      data: {
        bizId: orderId,
        state: '9',
        operateType: '0'
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        'X-Access-Token': this.data.token
      },
      success(res: any) {
        // console.error("success ==> " + JSON.stringify(res.data))
        if (res.data.code == 200) {
          that.onPullDownRefresh()
        } else {
          console.info(JSON.stringify(res))
        }
      },
      fail(err: any) {
        console.info(JSON.stringify(err))
      }
    })
  },
  // 订单操作
  orderOpt(param: any) {
    let type = param.currentTarget.dataset.type;
    let value = param.currentTarget.dataset.value;
    let that = this
    switch (type) {
      case 'cancelOrder':
        wx.showModal({
          title: '取消订单',
          content: '需要取消当前订单吗？',
          success: function (res) {
            if (res.confirm) {
              that.orderOptByOrderId(value, type)
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        break;
      case 'deleteOrder':
        // this.orderOptByOrderId(value, type)
        break;
      case 'addOrderByThis':
        this.addOrderAgain(value)
        break;
      default:
        console.error("type: default = " + type)
        break;
    }
  },
  addOrderAgain(item: any) {
    // console.error("doSubmitOrder-value=" + JSON.stringify(item))
    wx.navigateTo({
      url: '/pages/apps/store/storeHome/storeHome',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  

        const orderOldGoods: any = []
        if (item.goodsList != null && item.goodsList.length > 0) {
          const goodsList = item.goodsList
          for (let index = 0; index < goodsList.length; index++) {
            const item = goodsList[index];
            orderOldGoods.push({ goodsId: item.goodsId, saleNum: item.saleNum })
          }
        }
        // console.error("orderGoods=" + JSON.stringify(orderGoods))
        res.eventChannel.emit('acceptDataFromOpenerPage', { storeId: item.tenantId, orderOldGoods: orderOldGoods})
      }
    })

    // let store = { id: item.tenantId, storeName: item.storeName,deliveryHasSupport:item.deliveryHasSupport}

    // let selectedGoods = Array()
    // item.goodsList.forEach(element => {
    //   selectedGoods.push({
    //     id: element.goodsId,
    //     goodsCover: element.goodsCover,
    //     goodsSalePrice: element.goodsSalePrice,
    //     goodsFlagPrice: element.goodsFlagPrice,
    //     buyNum: element.saleNum
    //   })
    // });
    // wx.navigateTo({
    //   url: "/pages/order/orderSubmite/orderSubmite",
    //   events: {
    //   },
    //   success: function (res) {
    //     // 通过eventChannel向被打开页面传送数据  
    //     res.eventChannel.emit('acceptDataFromOpenerPage', {
    //       selectedGoods: selectedGoods,
    //       storeInfo: store
    //     })
    //   }
    // })
  }
})